#include "Stdafx.h"
#include "D3DXShaderInclude.h"

using namespace Vortex::Wrapper::Direct3D;


NativeShaderInclude::NativeShaderInclude(gcroot<D3DXShaderInclude^> includeProcessor) : _includeProcessor(includeProcessor) {
}

HRESULT NativeShaderInclude::Open(THIS_ D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) {
	return _includeProcessor->OpenInclude(IncludeType, pFileName, pParentData, ppData, pBytes);
}

HRESULT NativeShaderInclude::Close(THIS_ LPCVOID pData) {
	return _includeProcessor->CloseInclude(pData);
}

D3DXShaderInclude::D3DXShaderInclude() {
	_pNativeInclude = new NativeShaderInclude(this);
}

D3DXShaderInclude::~D3DXShaderInclude() {
	delete _pNativeInclude;
}

HRESULT D3DXShaderInclude::OpenInclude(THIS_ D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) {
	String^ content = GetFileContent((ShaderIncludeType)IncludeType, gcnew String(pFileName));
	char* pCharData = new char[content->Length + 1];

	//convert string to ASCII
	pin_ptr<const wchar_t> wszContentString = PtrToStringChars(content);
	WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wszContentString, -1, pCharData, content->Length + 1, NULL, NULL);

	*ppData = (void*)pCharData;
	*pBytes = content->Length;

	return S_OK;
}

HRESULT D3DXShaderInclude::CloseInclude(THIS_ LPCVOID pData) {
	if (pData) {
		delete pData;
	}
	return S_OK;
}